<template>
	<div class="bg">
		<el-card class="box-card">
			<div slot="header">
				<span>登录</span>
			</div>
			<el-form :model="form" ref="form" status-icon label-width="70px" :rules="rules">
				<el-form-item label="账号" prop="username">
					<el-input type="text" v-model="form.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input type="password" v-model="form.password" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleLogin">登录</el-button>
				</el-form-item>
			</el-form>
			<div class="bottom">
				<div>
					<el-link href="#/register" type="info">注册账户</el-link>
				</div>
				<div>
					<el-link href="#" type="info">忘记密码？</el-link>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script>
// 会在api下自动找
import { Admin } from '@/api';
import global from '@/plugins/global';

export default {
	data() {
		return {
			form: {
				username: 'admin',
				password: '123',
			},
			rules: {
				username: [
					// 非空验证
					{ required: true, message: '请输入账号名称！', trigger: 'blur' },
					// 有效性验证
					{ min: 3, max: 36, message: '长度在 3 到 36 个字符', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '请输入密码！', trigger: 'blur' },
					{ pattern: /^\d{3,}/, message: '密码至少3个数字', trigger: 'blur' }
				],
			}
		}
	},
	// 钩子函数
	created() {
		// 不在vue的范围，只能采用操作DOM的方法
		// document.title = "登录--CMS管理系统";
	},
	methods: {
		handleLogin() {
			// 表单验证
			this.$refs.form.validate(async (valid) => {
				// console.log(valid);	valid返回布尔值，表示是否通过校验
				// 通过校验发送axios
				if (valid) {
					// 浅拷贝
					let { status, msg, data } = await Admin.login({ ...this.form });
					if (status) {
						// 信息提示(elementUI组件)
						this.$message.success(msg);
						// 缓存数据(接收后台返回的数据，防止后面有用)
						sessionStorage.role_id = data.role_id;
						sessionStorage.user_id = data.user_id;
						sessionStorage.access_token = data.access_token;
						sessionStorage.refresh_token = data.refresh_token;
						// 动态路由重新加载
						global.is_route_unload = true;
						// 获取重定向参数redirect
						let { redirect } = this.$route.query;
						// 判读是否存在
						if (redirect) {
							// 重定向
							this.$router.push(redirect);
						} else {
							// 默认跳转页面（本质：切换组件）
							this.$router.push('/article/list');
						}
					} else {
						// 登录失败信息提示
						this.$message.error(msg);
					}
				}
			})
		},
	}
}
</script>

<!-- scoped: 防止重名的css冲突，如背景图等 -->
<style lang="less" scoped>
.bg {
	height: 100vh;
	background: url('img/login-bg.jpg') center no-repeat;
	background-size: cover;

	.box-card {
		position: fixed;
		right: 30px;
		top: 50%;
		transform: translateY(-50%);
		width: 400px;

		.bottom {
			display: flex;
			justify-content: space-between;

			a {
				color: black;
				text-decoration: none;
			}
		}
	}
}
</style>
